package com.yz.android_baozou.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ScrollView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;
import com.yz.android_baozou.R;
import com.yz.android_baozou.activity.MainPageDetailActivity;
import com.yz.android_baozou.adapter.Home_MainPage_RecyclerAdapter;
import com.yz.android_baozou.bean.MainPageBean;
import com.yz.android_baozou.decoration.SpacesItemDecoration;
import com.yz.android_baozou.helper.GlideImageLoader;
import com.yz.android_baozou.helper.OkhttpHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static android.content.ContentValues.TAG;

/**
 * Created by Administrator on 2016/10/31.
 */

public class HomePage_Home_Fragment extends Fragment {
    public String PATH_MAINPAGE = "http://dailyapi.ibaozou.com/api/v31/documents/latest";
    @Bind(R.id.recyclerView_homePage_home)
    RecyclerView recyclerViewHomePageHome;
    @Bind(R.id.fragment_banner)
    Banner fragmentBanner;
    @Bind(R.id.scoreView_homepage_home)
    PullToRefreshScrollView scoreViewHomepageHome;
    private List<MainPageBean.TopStoriesBean> list_TopStoriesbean = new ArrayList<>();
    private List<MainPageBean.DataBean> list_DataBean = new ArrayList<>();
    private Context mContext = null;
    private Home_MainPage_RecyclerAdapter recyclerAdapter;
    private MainPageBean homeMainPageBean;
    //声明字符串 用来替换旧的网址
    private String oldchar;
    private Menu myMenu;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_homepage_home, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);
        loadDataFromNet();
        scoreListener();

    }

    private void scoreListener() {
        scoreViewHomepageHome.setMode(PullToRefreshBase.Mode.BOTH);
        //滚动监听
        scoreViewHomepageHome.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //下拉刷新时 重置网址
                PATH_MAINPAGE = "http://dailyapi.ibaozou.com/api/v31/documents/latest";
                loadDataFromNet();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //http://dailyapi.ibaozou.com/api/v31/documents/latest?timestamp=14778864000&
                //首次上拉刷新时进行网址的拼接
                if (PATH_MAINPAGE.equals("http://dailyapi.ibaozou.com/api/v31/documents/latest")) {
                    if (homeMainPageBean != null) {
                        PATH_MAINPAGE = PATH_MAINPAGE + "?timestamp=" + homeMainPageBean.getTimestamp() + "&";
                        oldchar = homeMainPageBean.getTimestamp() + "";
                        loadDataFromNet();
                    }

                } else {
                    //当判断不是首次上拉刷新时进行网址的替换
                    PATH_MAINPAGE = PATH_MAINPAGE.replace(oldchar, homeMainPageBean.getTimestamp() + "");
                    oldchar = homeMainPageBean.getTimestamp() + "";
                    loadDataFromNet();
                }
            }
        });
    }

    private void loadDataFromNet() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = OkhttpHelper.getStringFromUrl(PATH_MAINPAGE);
                homeMainPageBean = recyclerAdapter.parseJsonToBean(json);
                if (homeMainPageBean != null) {
                    list_DataBean = homeMainPageBean.getData();
                    //轮播刷新
                    if (PATH_MAINPAGE.equals("http://dailyapi.ibaozou.com/api/v31/documents/latest")) {
                        //轮播
                        list_TopStoriesbean = homeMainPageBean.getTop_stories();
                        list_DataBean = homeMainPageBean.getData();
                        List<String> mList_imageUri = new ArrayList<>();
                        List<String> mList_titleUri = new ArrayList<>();
                        final List<String> mList_shareUrl = new ArrayList<String>();
                        for (int i = 0; i < list_TopStoriesbean.size(); i++) {
                            //获取图片的网址
                            mList_imageUri.add(list_TopStoriesbean.get(i).getImage());
                            //获取轮播的图片的标题
                            mList_titleUri.add(list_TopStoriesbean.get(i).getTitle());
                            //获得分享网址
                            mList_shareUrl.add(list_TopStoriesbean.get(i).getShare_url());
                        }
                        //轮播设置监听
                        fragmentBanner.setOnBannerClickListener(new OnBannerClickListener() {
                            @Override
                            public void OnBannerClick(int position) {
                                //获得点击的图片的分享网址
                                String url = mList_shareUrl.get(position - 1);
                                Bundle bundle = new Bundle();
                                bundle.putString("url", url);
                                Intent intent = new Intent(mContext, MainPageDetailActivity.class);
                                intent.putExtra("url", bundle);
                                mContext.startActivity(intent);
                            }
                        });
                        fragmentBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
                        fragmentBanner.setImageLoader(new GlideImageLoader());
                        //设置图片集合
                        fragmentBanner.setImages(mList_imageUri);
                        //设置标题集合（当banner样式有显示title时）
                        fragmentBanner.setBannerTitles(mList_titleUri);
                        //设置自动轮播，默认为true
                        fragmentBanner.isAutoPlay(true);
                        //设置轮播时间
                        fragmentBanner.setDelayTime(1500);
                        //设置指示器位置（当banner模式中有指示器时）
                        fragmentBanner.setIndicatorGravity(BannerConfig.CENTER);
                        //设置RecyclerView的适配器以及样式
                    }
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (PATH_MAINPAGE.equals("http://dailyapi.ibaozou.com/api/v31/documents/latest")) {
                            recyclerAdapter.reloadRecyclerView(list_DataBean, true);
                            fragmentBanner.start();
                        } else {
                            recyclerAdapter.reloadRecyclerView(list_DataBean, false);
                        }
                        //banner设置方法全部调用完毕时最后调用
                        scoreViewHomepageHome.onRefreshComplete();
                    }
                });
            }
        }).start();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //设置RecyclerView的中间的间距
        //使用线性布局管理器
        //设置RecyclerView的布局管理器
        //设置RecyclerView固定行高
        //创建适配器
        //设置RecyclerView的适配器
        if (myMenu != null) {
            Log.i(TAG, "onActivityCreated: 有没有走自己的清空清空清空");
            myMenu.clear();
        }
        recyclerViewHomePageHome.addItemDecoration(new SpacesItemDecoration(10));
        final LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerViewHomePageHome.setLayoutManager(manager);
        recyclerViewHomePageHome.setHasFixedSize(true);
        recyclerAdapter = new Home_MainPage_RecyclerAdapter(mContext, list_DataBean, recyclerViewHomePageHome);
        recyclerViewHomePageHome.setAdapter(recyclerAdapter);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main, menu);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


}
